﻿using System;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using CSVideoUploader.Util;

namespace CSVideoUploader.Client.Xina
{
    /// <summary>
    /// 渣浪工具类
    /// </summary>
    class XinaUtility
    {
        /// <summary>
        /// 编码用户名
        /// </summary>
        /// <param name="username">用户名明文</param>
        /// <returns></returns>
        public static string EncodeUsername(string username)
        {
            string str = HttpUtility.UrlEncode(username);
            str = Convert.ToBase64String(Encoding.UTF8.GetBytes(str));
            return str;
        }

        /// <summary>
        /// 编码密码
        /// </summary>
        /// <param name="password">密码明文</param>
        /// <param name="servertime">服务器时间</param>
        /// <param name="nonce">防重放参数</param>
        /// <param name="publicKey">RSA公钥</param>
        /// <returns></returns>
        public static string EncodePassword(string password, long servertime, string nonce, string publicKey)
        {
            // 待加密内容
            StringBuilder buf = new StringBuilder();
            buf.Append(servertime).Append("\t").Append(nonce).Append("\n").Append(password);

            // 准备密钥
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024);
            RSAParameters rsap = new RSAParameters();
            rsap.Exponent = new byte[] { 1, 0, 1 };
            rsap.Modulus = DataUtility.Hex2Bytes(publicKey);
            rsa.ImportParameters(rsap);

            // 使用rsa加密
            byte[] enBytes = rsa.Encrypt(Encoding.UTF8.GetBytes(buf.ToString()), false);
            return DataUtility.Bytes2Hex(enBytes);
        }
    }
}
